package com.ludomancy.timescape;

import java.awt.Point;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;

public class Game
{
	public static Game game;
	public static final int TILE_SIZE = 20;
	public static final int MAX_TIME = 100;
	public int currentTime = 0;
	private Planet initialTerrain;
	public Planet currentTerrain;
	public Vector entities = new Vector();
	public Vector initialEntities = new Vector();
	public static Random randomizer = new Random(1978);
	
	public Game(int landscapeWidth, int landscapeHeight)
	{
		game = this;
		initialTerrain = new Planet("/terrain.map");
		try
		{
			currentTerrain = (Planet) initialTerrain.clone();
		} 
		catch (CloneNotSupportedException e)
		{
		}
	}
	
	public boolean isWithin(Point tilePos)
	{
		return tilePos.x >= 0 && tilePos.x < Game.game.currentTerrain.width && tilePos.y >= 0 && tilePos.y < Game.game.currentTerrain.height;
	}
	
	public Entity getEntityUnder(Point tilePos)
	{
		for (Iterator iter = entities.iterator(); iter.hasNext();)
		{
			Entity entity = (Entity) iter.next();
			if(entity.tx == tilePos.x && entity.ty == tilePos.y)
			{
				return entity;
			}
		}
		return null;
	}
	
	private void reset()
	{
		entities.clear();
		entities.addAll(initialEntities);
		for (int i = 0; i < entities.size(); i++)
		{
			Entity entity = (Entity) entities.elementAt(i);
			entity.reset();
		}
		// reset the fucking map
		try
		{
			currentTerrain = (Planet) initialTerrain.clone();
		} 
		catch (CloneNotSupportedException e)
		{
		}
	}
	
	public void setTime(int newValue)
	{
		reset();
		for (currentTime = 0; currentTime < newValue; currentTime++)
		{
			Vector updateEntities = new Vector();
			updateEntities.addAll(entities);
			for (int i = 0; i < updateEntities.size(); i++)
			{
				Entity entity = (Entity) updateEntities.elementAt(i);
				if(entity.initialTime <= currentTime)
				{
					entity.affectEnvironment();
				}
			}
			for (int i = 0; i < updateEntities.size(); i++)
			{
				Entity entity = (Entity) updateEntities.elementAt(i);
				if(entity.initialTime <= currentTime)
				{
					entity.evolve();
				}
			}
		}
		currentTime = newValue;
	}

	public void addEntity(Entity entity, boolean userGenerated)
	{
		if(getEntityUnder(new Point(entity.tx,entity.ty)) == null)
		{
			entities.add(entity);
			if(userGenerated)
			{
				initialEntities.add(entity);
			}
		}
	}

	public void removeEntity(Entity e)
	{
		entities.remove(e);
		initialEntities.remove(e);
	}
}
